package linkedlist;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2021/12/30 22:50
 * 给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。
 * https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
 */
public class RemoveNthFromEnd {
    static class ListNode {
        int val;

        ListNode next;

        ListNode() {

        }

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        //记录节点从index 1 开始的preNode
        List<ListNode> preIndex = new ArrayList<>();
        ListNode cur = head;
        while (cur != null) {
            preIndex.add(cur);
            cur = cur.next;
        }
        int index = preIndex.size() - n;
        if (index == 0) {
            return head.next;
        }
        ListNode listNode = preIndex.get(index - 1);
        if (n == 1) {
            listNode.next = null;
        }else{
            listNode.next = preIndex.get(index + 1);
        }
        return head;
    }

    public ListNode removeNthFromEnd1(ListNode head, int n) {
        ListNode dummyNode = new ListNode(0);
        dummyNode.next = head;
        ListNode first = dummyNode;
        ListNode second = dummyNode;
        for (int i = 0; i <= n; i++) {
            first = first.next;
        }
        while (first != null) {
            first=first.next;
            second = second.next;
        }
        second.next = second.next.next;
        return dummyNode.next;
    }
}
